<template>
  <div class="watchlist-drawer" :class="{ 'is-open': isOpen }">
    <div class="drawer-header">
      <h3>Watchlist</h3>
    </div>
    <div class="drawer-content">
      <div class="search-box">
        <input type="text" v-model="searchQuery" placeholder="Search symbols..." />
      </div>
      <div class="watchlist">
        <div v-for="(item, index) in filteredWatchlist" :key="item.symbol" 
             class="watchlist-item" 
             @click="selectSymbol(item.symbol)"
             :class="{ 
               'active': currentSymbol === item.symbol,
               'keyboard-selected': selectedIndex === index 
             }">
          <div class="symbol-info">
            <span class="symbol">{{ item.symbol }}</span>
            <span class="name">{{ item.name }}</span>
          </div>
          <!-- <div class="price-info">
            <span class="price" :class="{ 'up': item.change > 0, 'down': item.change < 0 }">
              {{ item.price }}
            </span>
            <span class="change" :class="{ 'up': item.change > 0, 'down': item.change < 0 }">
              {{ item.change > 0 ? '+' : ''}}{{ item.change }}%
            </span>
          </div> -->
          <button @click.stop="confirmDelete(item.symbol)">Delete</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { userConfig } from '../config/userConfig';

export default {
  name: 'WatchlistDrawer',
  props: {
    currentSymbol: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isOpen: true,
      searchQuery: '',
      selectedIndex: -1
    }
  },
  computed: {
    ...mapState(['watchlist']),
    filteredWatchlist() {
      if (!this.searchQuery) return this.watchlist
      const query = this.searchQuery.toLowerCase()
      return this.watchlist.filter(item => 
        item.symbol.toLowerCase().includes(query) || 
        item.name.toLowerCase().includes(query)
      )
    }
  },
  mounted() {
    this.$store.dispatch('updateWatchlist');
    window.addEventListener('keydown', this.handleKeyDown);
  },
  beforeUnmount() {
    this.$eventBus.$off('symbolSaved', this.$store.dispatch('updateWatchlist'));
    window.removeEventListener('keydown', this.handleKeyDown);
  },
  methods: {
    async removeStock(symbol) {
      try {
        const confirmed = confirm('Are you sure you want to delete this stock?');
        if (!confirmed) return;
        const response = await fetch(`/api/favorite/stocks/${symbol}?user_id=${userConfig.userId}`, {
          method: 'DELETE'
        });
        if (response.ok) {
          this.$store.dispatch('updateWatchlist');
        } else {
          console.error('Failed to delete stock:', response.statusText);
        }
      } catch (error) {
        console.error('Error deleting stock:', error);
      }
    },
    confirmDelete(symbol) {
      this.removeStock(symbol);
    },
    toggleDrawer() {
      this.isOpen = !this.isOpen
    },
    selectSymbol(symbol) {
      console.log('[WatchlistDrawer] selectSymbol called with:', symbol)
      this.selectedIndex = this.filteredWatchlist.findIndex(item => item.symbol === symbol);
      this.$emit('symbol-selected', symbol)
    },
    handleKeyDown(event) {
      if (!this.isOpen || this.filteredWatchlist.length === 0) return;
      
      switch(event.key) {
        case 'ArrowUp':
          event.preventDefault();
          this.selectedIndex = this.selectedIndex <= 0 
            ? this.filteredWatchlist.length - 1 
            : this.selectedIndex - 1;
          this.ensureSelectedVisible();
          break;
        case 'ArrowDown':
          event.preventDefault();
          this.selectedIndex = this.selectedIndex >= this.filteredWatchlist.length - 1 
            ? 0 
            : this.selectedIndex + 1;
          this.ensureSelectedVisible();
          break;
      }

      this.selectSymbol(this.filteredWatchlist[this.selectedIndex].symbol);

    },
    ensureSelectedVisible() {
      if (this.selectedIndex >= 0) {
        const elements = document.getElementsByClassName('watchlist-item');
        if (elements[this.selectedIndex]) {
          elements[this.selectedIndex].scrollIntoView({ block: 'nearest' });
        }
      }
    },
  }
}
</script>

<style scoped>
.watchlist-drawer {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 200px;
  background: #ffffff;
  color: #131722;
  transition: transform 0.3s ease;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #e0e3eb;
}

.watchlist-drawer:not(.is-open) {
  transform: translateX(calc(100% - 30px));
}

.drawer-header {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e0e3eb;
  background: #f8f9fd;
}

.drawer-header h3 {
  margin: 0;
  font-size: 16px;
  color: #131722;
}

.toggle-button {
  background: none;
  border: none;
  color: #787b86;
  cursor: pointer;
  padding: 5px;
}

.toggle-button:hover {
  color: #131722;
}

.drawer-content {
  flex: 1;
  overflow-y: auto;
}

.search-box {
  padding: 10px;
  border-bottom: 1px solid #e0e3eb;
  background: #ffffff;
}

.search-box input {
  width: 90%;
  padding: 8px;
  background: #ffffff;
  border: 1px solid #e0e3eb;
  color: #131722;
  border-radius: 4px;
}

.search-box input:focus {
  outline: none;
  border-color: #2196f3;
}

.watchlist-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #e0e0e0;
  transition: background-color 0.3s;
}

.watchlist-item:hover {
  background-color: #f9f9f9;
}

.watchlist-item.active {
  background-color: #e0f7fa;
}

.watchlist-item.keyboard-selected {
  background-color: rgba(0, 123, 255, 0.1);
  border-left: 3px solid #007bff;
}

.symbol-info {
  display: flex;
  flex-direction: column;
}

.symbol {
  font-weight: bold;
  margin-bottom: 2px;
  color: #131722;
}

.name {
  font-size: 12px;
  color: #787b86;
}

button {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #d32f2f;
}
</style>
